/*
 * @Description:
 * @Author: liyuhao
 * @Date: 2021-08-16 09:54:56
 * @LastEditors: liyuhao
 * @LastEditTime: 2021-09-03 17:29:32
 */
import {useCallback} from 'react';
import {message} from 'antd';
import {useSetState} from 'ahooks';

export interface UseDownloadFileProps {
    request: any; // 需是umi-request
    fileName?: string;
}

const useDownloadFile = () => {
    const [state, setState] = useSetState<{ loading: boolean }>({loading: false});

    const run = useCallback(async (props: UseDownloadFileProps) => {
        const {request, fileName} = props;
        setState({loading: true});
        return new Promise(async (resolve, reject) => {
            try {
                const resJson = await request();
                let _fileName = fileName;
                const {data, headers} = resJson || {};
                if (!fileName) {
                    const ContentDisposition = headers.get('Content-Disposition');
                    _fileName = decodeURIComponent(ContentDisposition?.split('filename=').pop());
                }
                const blob = new Blob([data]);
                if ('download' in document.createElement('a')) {
                    // 非IE下载
                    const eLink = document.createElement('a');
                    eLink.download = _fileName || '';
                    eLink.style.display = 'none';
                    eLink.href = URL.createObjectURL(blob);
                    document.body.appendChild(eLink);
                    eLink.click();
                    URL.revokeObjectURL(eLink.href); // 释放URL 对象
                    document.body.removeChild(eLink);
                } else {
                    // IE10+下载
                    (navigator as any).msSaveBlob(blob, _fileName);
                }
                resolve(undefined);
            } catch (err: any) {
                message.error('导出文件时出现错误！' + '\n' + (err?.message || err));
                reject(err);
            }
            setState({loading: false});
        });
    }, []);

    return {
        ...state,
        run,
    };
};

export default useDownloadFile;

